/* eslint-disable no-mixed-operators */
import React from 'react';
import {Spin, Card, Button, Row, Col, Form} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS} from '../constants';
import {addApplyReport} from './api';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import {currency} from '../Enum';
import {injectIntl, language} from './intl';
import WrappedDatePicker from '../common/WrappedDatePicker';
import WrappedSelect from '../common/WrappedSelect';
import styles from './style.css';
import Return from '../common/Return';
import {newOrUpdateOrderValidator} from './validator';
const FormItem = Form.Item;

const currencyToList = currency.toList(language);
class AddPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        data: {sourceCurrency: 1},
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const data = this.state.data;
        const isValid = newOrUpdateOrderValidator(data);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            brandId: data.brandId,
            sourceCurrency: data.sourceCurrency,
            targetCurrency: data.targetCurrency,
            rate: data.rate,
            beginDate: data.beginDate,
            endDate: data.endDate,
        };
        this.setState({loading: true});
        addApplyReport(condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, isValidate, loading} = this.state;
        const {brands} = this.props.initEnumData;
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'addPanel.column.common',
                        defaultMessage: '汇率信息'
                    })}>
                        <Form>
                            <Row>
                                <Row>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'addPanel.form.brands',
                                                defaultMessage: '品牌'
                                            })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.brandId ? 'error' : null} required>
                                            <WrappedSelect
                                                allowClear
                                                name="brandId"
                                                options={brands}
                                                value={data.brandId}
                                                onChange={this.onChange}/>
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'addPanel.form.sourceCurrency',
                                            defaultMessage: '本位币'
                                        })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.sourceCurrency || (data.sourceCurrency === data.targetCurrency) ? 'error' : null} required>
                                            <WrappedSelect
                                                allowClear
                                                name="sourceCurrency"
                                                options={currencyToList}
                                                value={data.sourceCurrency}
                                                onChange={this.onChange}/>
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'addPanel.form.targetCurrency',
                                            defaultMessage: '目标币种'
                                        })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.targetCurrency || (data.targetCurrency === data.sourceCurrency) ? 'error' : null} required>
                                            <WrappedSelect
                                                allowClear
                                                name="targetCurrency"
                                                options={currencyToList}
                                                value={data.targetCurrency}
                                                onChange={this.onChange}/>
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'addPanel.form.rate',
                                                defaultMessage: '汇率'
                                            })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.rate ? 'error' : null} required>
                                            <LocalizeInputNumber
                                                precision={2}
                                                name="rate"
                                                value={data.rate}
                                                onBlur={this.onChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'addPanel.form.beginDate',
                                            defaultMessage: '生效日期'
                                        })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.beginDate ? 'error' : null} required>
                                            <WrappedDatePicker
                                                name="beginDate"
                                                value={data.beginDate}
                                                onChange={this.onChange} />
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'addPanel.form.endDate',
                                            defaultMessage: '失效日期'
                                        })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.endDate || data.endDate < data.beginDate ? 'error' : null} required>
                                            <WrappedDatePicker
                                                name="endDate"
                                                value={data.endDate}
                                                onChange={this.onChange} />
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Row>
                        </Form>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'addPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

AddPanel.propTypes = {
    initEnumData: PropTypes.object.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch
} from './actions';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: item.name,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(AddPanel));
